package com.github.baichuan.iot.gateway.handler;

import com.github.baichuan.iot.protocol.codec.MessageEncodeContext;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.function.Consumer;

/**
 * 入站消息处理器
 * 用于实现对入站消息的处理，如将入站报文写入外部存储等
 */
@ChannelHandler.Sharable
public class InboundConsumeHandler extends ChannelInboundHandlerAdapter {
    private Consumer<MessageEncodeContext> consumer;

    public InboundConsumeHandler(Consumer<MessageEncodeContext> consumer) {
        this.consumer = consumer;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg){
        if(msg instanceof MessageEncodeContext){
            MessageEncodeContext inbound = (MessageEncodeContext) msg;
            consumer.accept(inbound);
        }

        ctx.fireChannelRead(msg);
    }
}
